<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;

use think\facade\Env;
use think\facade\Hook;
use think\Loader;
use Zhuzhichao\IpLocationZh\Ip;

// 应用公共文件

define("Mortal_ADDON_PATH", Env::get('root_path') . "addons");

//数组递归
if(!function_exists('array_recursion')){
    function array_recursion($array,$pid=0) {
        $new_array = [];
        if(is_array($array)){
            foreach($array as $value){
                if(isset($value['conditions'])&&!empty($value['conditions'])){
                    $value['conditions'] = "/".$value['conditions'];
                }
                if($value['pid'] == $pid){
                    $children = array_recursion($array, $value['id']);
                    if($children){
                        $value['children'] = $children;
                    }
                    $new_array[] = $value;
                }
            }
            return $new_array;
        }else{
            return $array;
        }
    }
}
if(!function_exists('get_s_c')){
    function get_s_c($key,$default='') {
        if($key){
            $res = Db::name('system')->where(['s_key'=>$key,'status'=>1])->value('content');
            if($res){
                return $res;
            }else{
                return $default;
            }
        }else{
            return $default;
        }
    }
}
if(!function_exists('get_login_token')){
    /**
     * 生成用户登录token
     * @return string
     * @throws \Random\RandomException
     */
    function get_login_token()
    {
        $token = bin2hex(random_bytes(32));
        return $token;
    }
}
/**
 * 获取插件类的类名
 * @param strng $name 插件名
 */
if(!function_exists('get_addons_class')){
    function get_addons_class($name, $type = '', $class = null)
    {
        $name = Loader::parseName($name);
        // 处理多级控制器情况
        if (!is_null($class) && strpos($class, '.')) {
            $class = explode('.', $class);
            foreach ($class as $key => $cls) {
                $class[$key] = Loader::parseName($cls, 1);
            }
            $class = implode('\\', $class);
        } else {
            $class = Loader::parseName(is_null($class) ? $name : $class, 1);
        }

        switch ($type) {
            case 'controller':
                $namespace = "\\addons\\" . $name . "\\controller\\" . $class;
                break;
            default:
                $namespace = "\\addons\\" . $name . "\\" . $class;
        }

        return class_exists($namespace) ? $namespace : '';
    }
}
/**
 * 处理插件钩子
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
if(!function_exists('hook')){
    function hook($hook,$params=array())
    {
        Hook::listen($hook,$params);
    }
}
/**
 * 获取插件类的配置文件数组
 * @param string $name 插件名
 */
if(!function_exists('get_addon_config')) {
    function get_addon_config($name)
    {
        $class = get_addons_class($name);
        if (class_exists($class)) {
            $addon = new $class();
            return $addon->getConfig();
        } else {
            return array();
        }
    }
}

/**
 * 插件显示内容里生成访问插件的url
 * @param $url
 * @param array $param
 * @return bool|string
 * @param bool|string $suffix 生成的URL后缀
 * @param bool|string $domain 域名
 */
if(!function_exists('addon_url')) {
    function addon_url($url, $param = [])
    {
        $url = parse_url($url);
        $case = config('url_convert');
        $addons = $case ? Loader::parseName($url['scheme']) : $url['scheme'];
        $controller = $case ? Loader::parseName($url['host']) : $url['host'];
        $action = trim($case ? strtolower($url['path']) : $url['path'], '/');

        /* 解析URL带的参数 */
        if (isset($url['query'])) {
            parse_str($url['query'], $query);
            $param = array_merge($query, $param);
        }

        /* 基础参数 */
        $params = array(
            '_addons'     => $addons,
            '_controller' => $controller,
            '_action'     => $action,
        );
        $params = array_merge($params, $param); //添加额外参数

        return url('Addons/execute', $params);
    }
    /**
     *添加ADN编辑字段必填以及唯一判断
     *
     * **/
    if(!function_exists('add_edit_verify')){
        function add_edit_verify($data,$required = [], $one = [],$table=''){
            if($one && !$table){
                return ['code'=>1,'msg'=>'need table'];
            }
            if(!$data || !is_array($data)){
                return ['code'=>1,'msg'=>'数据格式错误，need Array'];
            }
            foreach($data as $k=>$v){
                if($required && in_array($k,$required) && empty($v)){
                    return ['code'=>1,'msg'=>'字段：'.$k.'必填！required'];
                }
                if($one && in_array($k,$one)){
                    $where[] = [$k,'=',$v];
                    if(isset($data['id'])&&!empty($data['id'])){
                        $where[] = ['id','<>',$data['id']];
                    }
                    $old = db($table)->where($where)->find();
                    if($old){
                        return ['code'=>1,'msg'=>$k.'不可重复！'];
                    }
                }
            }
            return ['code'=>200,'msg'=>'ok'];
        }
    }
    if(!function_exists('get_addons_list')){
        function get_addons_list(){
            $addons_path = Mortal_ADDON_PATH;
            $dirs = array_map('basename',glob($addons_path.'/*', GLOB_ONLYDIR));
            if($dirs === false || !file_exists($addons_path)){
                return ['code'=>1,'msg'=>'插件目录不可读，或不存在'];
            }
            $addons = [];
            //查询已安装插件
            $list = db('addons')->select();
            foreach($list as $addon){
                $addon['install'] = 1;
                $class = get_addons_class($addon['name']);
                if(!$class){
                    continue;
                }
                $c = new $class();
                if(method_exists($c,'update')){
                    $addon['update'] = 1;
                }else{
                    $addon['update'] = 2;
                }
                if($c->config_file){
                    $addon['is_config'] = 1;
                }else{
                    $addon['is_config'] = 2;
                }
                $addons[Loader::parseName($addon['name'])]	= $addon;
            }
            foreach ($dirs as $value) {

                if(!isset($addons[$value])){
                    $class = get_addons_class($value);
                    if(!class_exists($class)){ // 实例化插件失败忽略执行
                        continue;
                    }
                    $obj = new $class;
                    $addons[$value]	= $obj->info;
                    if($addons[$value]){
                        if(method_exists($obj,'update')){
                            $addons[$value]['update'] = 1;
                        }else{
                            $addons[$value]['update'] = 2;
                        }
                        if($obj->config_file){
                            $addons[$value]['is_config'] = 1;
                        }else{
                            $addons[$value]['is_config'] = 2;
                        }
                        $addons[$value]['install'] = 2;
                        $addons[$value]['status'] = 3;
                    }
                }
            }
            usort($addons, function($a, $b) {
                return $a['install'] <=> $b['install'];
            });
            return $addons;
        }
    }
    if(!function_exists('delete_addons_methods')){
        function delete_addons_methods($methods){
            foreach ($methods as $k=>$method) {
                if(in_array($method,['install','uninstall','update','__construct','assign','show','display','fetch','checkInfo','getName','getConfig','getInfo'])){
                    unset($methods[$k]);
                }
            }
            return $methods;
        }
    }
    if(!function_exists('mor_addons_unzip')){
        function mor_addons_unzip($filename){
            //解压缩
            $zip = new \ZipArchive;
            //要解压的文件
            $zip_file = $filename;
            $res = $zip->open($zip_file);
            if(!$res){
                return false;
            }
            if(!file_exists(Mortal_ADDON_PATH)) {
                mkdir(Mortal_ADDON_PATH,755);
            }
            $res_s = $zip->extractTo(Mortal_ADDON_PATH);
            $zip->close();
            if(!$res_s){
                return false;
            }
            return true;
        }
    }
    if(!function_exists('get_ip_address')){
        function get_ip_address($ip){
            if($ip){
                $ipaddress = Ip::find($ip);
                return is_array($ipaddress) ? $ip.'/'.implode(' ',$ipaddress) : $ip;
            }else{
                return $ip;
            }
        }
    }
}